package com.tizona.service.impl;

import com.tizona.TarifdConfig;
import com.tizona.service.tarification.Restriction;
import com.tizona.dao.jdbc.FastStatement;
import com.tizona.service.TarifManager;

import java.util.Hashtable;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.math.BigDecimal;

/**
 * Created by Vitaliy Kim.
 * Date: 23.08.2005
 * Time: 22:21:10
 */

public class TarifManagerImpl extends BaseManager implements TarifManager {

    private TarifdConfig cfg;
    private Hashtable <String, Tarification> all_tp = new Hashtable <String, Tarification>();
    private Hashtable <String, Restriction> all_q = new Hashtable <String, Restriction>();
    private FastStatement fstmtTarification, fsmtRestriction;

    public TarifManagerImpl(TarifdConfig cfg) throws SQLException {
        this.cfg = cfg;

        fstmtTarification = cfg.sql.prepare("SELECT CLASSNAME from T_PLANS WHERE (TYPE='T' or TYPE='U') and TP_ID=?");
        fsmtRestriction = cfg.sql.prepare("SELECT CLASSNAME from T_PLANS WHERE (TYPE='Q' or TYPE='U')and TP_ID=?");

    }

    public Tarification getTarification(String tp_id) throws Exception {
        Tarification tp;
        if( all_tp.containsKey(tp_id))
        {
            tp = all_tp.get(tp_id);
        }
        else
        {
            fstmtTarification.setBigDecimal(1, new BigDecimal(tp_id));
            ResultSet tp_res = cfg.sql.query(fstmtTarification);
            if(!tp_res.next())
            {
                throw new Exception("No tarification ClassName for TP_ID="+tp_id);
            }
            String tarification_name = "com.tizona.custom." + tp_res.getString("CLASSNAME");

            tp = (Tarification) Class.forName(tarification_name).newInstance();
            tp.cfg=cfg;
            tp.id=tp_id;
            all_tp.put(tp_id,tp);
        }
        return tp;
    }

    public Restriction getRestriction(String q_id) throws Exception {
        Restriction restriction;
        if( all_q.containsKey(q_id))
        {
            restriction = all_q.get(q_id);
        }
        else
        {
            fsmtRestriction.setBigDecimal(1, new BigDecimal(q_id));
            ResultSet tp_res = cfg.sql.query(fsmtRestriction);
            if(!tp_res.next())
            {
                throw new Exception("No restrictin ClassName for QT_ID="+q_id);
            }
            String tarification_name = "com.tizona.custom." + tp_res.getString("CLASSNAME");

            restriction = (Restriction) Class.forName(tarification_name).newInstance();
            all_q.put(q_id,restriction);
        }
        return restriction;
    }
}